<?php 
if (!class_exists('Plugin')) {
	die('Hacking attemp!');
}

class PluginYii_ModuleYii
extends Module
{
	
	protected $app;
	
	public function Init(){
	}
	
	public function CreateApp($sType, $bForce = false){
		if($this->app && !$bForce){
			return $this->app;
		}
		$aConfig = $this->GetConfig($sType);
		$oApp = null;
		switch($sType){
			case 'web':
				$this->Hook_Run('plugin_yii_app_create_before');
				$oApp = Yii::createWebApplication($aConfig);
				$this->app = $oApp;
				$this->Hook_Run('plugin_yii_app_create_after', compact('oApp', 'sType'));
				break;
			case 'console':
				$this->Hook_Run('plugin_yii_app_create_before');
				$oApp = Yii::createConsoleApplication($aConfig);
				$this->app = $oApp;
				$this->Hook_Run('plugin_yii_app_create_after', compact('oApp', 'sType'));
				break;
		}
		if($oApp){
			$this->app = $oApp;
			$oApp->onBeginRequest(new CEvent($oApp));
		}
		return $oApp;
	}
	
	public function GetMainConfig(){
		return Config::Get('plugin.yii.app');
	}
	
	public function GetConfig($sType){
		$sConfigKey = null;
		$sConfigPrefix = 'plugin.yii.';
		switch($sType){
			case 'web':
				$sConfigKey = 'webApp';
				break;
			case 'console':
				$sConfigKey = 'consoleApp';
				break;
		}
		$aConfig = $this->GetMainConfig();
		if($sConfigKey){
			$aConfig = func_array_merge_assoc(Config::Get($sConfigPrefix.$sConfigKey), $aConfig);
		}
		return $aConfig;
	}
	
	public function GetSapiType(){
		return PHP_SAPI == 'cli' ? 'console' : 'web';
	}
	
	public function App($sType = null){
		if(!$sType){
			$sType = $this->GetSapiType();
		}
		$oApp = $this->CreateApp($sType);
		return $oApp;
	}
	
	public function IsLoaded(){
		return !empty($this->app);
	}
	
}

?>